/**
 * 
 */
package org.textplantform.common.core;

import java.net.UnknownHostException;
import java.util.Iterator;

import org.springframework.util.StringUtils;
import org.textplantform.common.api.LabeledRecord;
import org.textplantform.common.api.MongoDBRecordWriter;
import org.textplantform.common.api.Record;
import org.textplantform.common.api.core.Result;

import com.google.gson.Gson;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;

/**
 * @author alex
 *
 */
public class DefaultMongoRecordWriter implements MongoDBRecordWriter {
	MongoDBClient mdc;
	String dbName;
	String collectionName;
	public DefaultMongoRecordWriter(MongoDBClient mdc,String dbName,String collectionName) {
		this.mdc = mdc;
		this.dbName = dbName;
		this.collectionName = collectionName;
	}
	@Override
	public Result writeRecord(Record r) {
		try {
			return insert(r);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return new ExceptionResult(e);
		}

	}

	@Override
	public Result writeRecord(Iterator<Record> rs) {
		while (rs.hasNext()) {
			Record r = rs.next();
			try {
				insert(r);
			} catch (UnknownHostException e) {
				e.printStackTrace();
				return new ExceptionResult(e);
			}
		}

		return new SuccessResult("insert mongo success");

	}

	@Override
	public Result writeLabeledRecord(LabeledRecord r) {
		try {
			return insert(r);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return new ExceptionResult(e);
		}
	}

	@Override
	public Result writeLabeledRecord(Iterator<LabeledRecord> rs) {
		while (rs.hasNext()) {
			LabeledRecord r = rs.next();
			try {
				insert(r);
			} catch (UnknownHostException e) {
				e.printStackTrace();
				return new ExceptionResult(e);
			}
		}

		return new SuccessResult("insert mongo success");
	}

	public Result insert(Object obj) throws UnknownHostException {
		Mongo mongo = mdc.getMongo();
		DB myMongo = mongo.getDB("ClassifiedTextDB");
		DBCollection collection = myMongo.getCollection("ClassifiedDocuments");
		Gson gson = new Gson();
		DBObject dbObject = (DBObject) JSON.parse(gson.toJson(obj));
		WriteResult wr = collection.insert(dbObject, WriteConcern.ACKNOWLEDGED);
		if(StringUtils.hasText(wr.getError())){
			return new ExceptionResult(new Exception(wr.getError()));
		}
		return new SuccessResult("insert mongo success");
	}

	@Override
	public Mongo getConnection() {
		return mdc.getMongo();
	}

}
